package com.huiyeji.hui.utils;

import com.huiyeji.hui.exception.ValidationException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * @author zhaoduo
 */
public class ValidateUtil {

    /**
     * 分析BindingResult,根据情况抛错
     * @param bindingResult bindingResult
     */
    public static void analyzeBindingResult(BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            List<FieldError> errors = bindingResult.getFieldErrors();
            if (!CollectionUtils.isEmpty(errors)){
                StringBuilder stringBuilder = new StringBuilder();
                for (FieldError error : errors) {
                    stringBuilder.append(error.getDefaultMessage()).append(";");
                }
                stringBuilder.deleteCharAt(stringBuilder.length()-1);
                throw new ValidationException(stringBuilder.toString());
            }
        }
    }
}
